from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from django.http import StreamingHttpResponse  # 新增导入
from django.views.decorators.http import require_POST
from django.utils import timezone
from django.views.decorators.csrf import csrf_protect
from django.http import JsonResponse
from coach.models.ai_patient_models import AIPatient
from coach.models import ChatRecord  # 导入聊天记录模型
from cozepy import Coze, TokenAuth, Message, COZE_CN_BASE_URL, ChatEventType
import json
import time
import logging
from .forms import CustomLoginForm
import os
from coach.utils.ai_client import coze_client

logger = logging.getLogger(__name__)

def dashboard(request):
    return render(request, 'student/dashboard.html')

def ai_patient_list(request):
    """展示所有评分标准列表"""
    ai_patient_items = AIPatient.objects.all()
    return render(request, 'student/ai_patient_list.html', {
        'ai_patient_items': ai_patient_items,
        'title': '向AI病人问诊'
    })

@csrf_protect
@require_POST
def get_ai_response(request):
    try:
        patient_id = request.POST.get('patient_id')
        message = request.POST.get('message', '')
        user = request.user  # 获取当前当前登录用户

        if not patient_id or not message or not user.is_authenticated:
            return JsonResponse({
                'status': 'error',
                'message': '缺少参数或未登录'
            })
            
        # 获取病人信息
        try:
            patient = AIPatient.objects.get(id=patient_id)
            bot_id = patient.bot_id
        except AIPatient.DoesNotExist:
            return JsonResponse({
                'status': 'error',
                'message': 'AI病人不存在'
            })
        
        # 保存用户发送的消息
        ChatRecord.objects.create(
            student=user,
            ai_patient=patient,
            sender_type='student',
            message_content=message
        )
        
        # 创建响应对象
        response = StreamingHttpResponse(content_type='text/event-stream')
        response['Cache-Control'] = 'no-cache'

        # 构建消息并调用Coze API
        def generate():
            ai_response_content = ""  # 累积AI回复内容
            try:
                for event in coze_client.chat.stream(
                    bot_id=bot_id,
                    user_id=str(user.id),
                    additional_messages=[
                        Message.build_user_question_text(message),
                    ],
                ):
                    if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
                        if event.message is not None:
                            ai_response_content += event.message.content
                            yield f"data: {json.dumps({'type': 'delta', 'content': event.message.content})}\n\n"
                    if event.event == ChatEventType.CONVERSATION_CHAT_COMPLETED:
                        # 保存AI回复的完整内容
                        ChatRecord.objects.create(
                            student=user,
                            ai_patient=patient,
                            sender_type='ai',
                            message_content=ai_response_content
                        )
                        yield f"data: {json.dumps({
                            'type': 'complete', 
                            'token_usage': event.chat.usage.token_count
                        })}\n\n"
                        break
            
            except Exception as e:
                logger.error(f"Coze API调用错误: {str(e)}")
                yield f"data: {json.dumps({'type': 'error', 'message': str(e)})}\n\n"

        response.streaming_content = generate()
        return response
        
    except Exception as e:
        logger.error(f"处理AI响应错误: {str(e)}")
        return JsonResponse({
            'status': 'error',
            'message': str(e)
        })